package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.dto.SurveyQuestionSectionDto;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.event.EventPlanTask;
import com.caiheng.api.entity.event.EventPointQr;
import com.caiheng.api.entity.event.EventPointQrInfo;
import com.caiheng.api.entity.survey.Survey;
import com.caiheng.api.entity.survey.SurveyQuestion;
import com.caiheng.api.entity.survey.SurveyUserRecord;
import com.caiheng.api.entity.survey.SurveyUserRecordInfo;
import com.caiheng.api.entity.sys.SysNotice;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.EstateRoomService;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.estate.PropertyService;
import com.caiheng.api.service.event.EventPlanTaskService;
import com.caiheng.api.service.event.EventPointQrInfoService;
import com.caiheng.api.service.event.EventPointQrService;
import com.caiheng.api.service.survey.SurveyQuestionService;
import com.caiheng.api.service.survey.SurveyService;
import com.caiheng.api.service.survey.SurveyUserRecordInfoService;
import com.caiheng.api.service.survey.SurveyUserRecordService;
import com.caiheng.api.service.sys.SysConfigService;
import com.caiheng.api.service.sys.SysNoticeService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/survey")//url:模块/资源/{}/细分
public class SurveyController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SurveyService surveyService;
    @Resource
    private SurveyQuestionService questionService;
    @Resource
    private SurveyUserRecordService surveyUserRecordService;
    @Resource
    private SurveyUserRecordInfoService surveyUserRecordInfoService;
    @Resource
    private EstateService estateService;
    @Resource
    private PropertyService propertyService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private SysNoticeService sysNoticeService;
    @Resource
    private EventPlanTaskService eventPlanTaskService;
    @Resource
    private EventPointQrService eventPointQrService;
    @Resource
    private EventPointQrInfoService eventPointQrInfoService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址
    @Value("${web.imgPrefix}")
    private String imgPrefix;

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            System.out.println("survey/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_type = jsonRequest.containsKey("survey_type") ? jsonRequest.getInt("survey_type") : 0;
            int is_my = jsonRequest.containsKey("is_my") ? jsonRequest.getInt("is_my") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<Integer> estateIds = new ArrayList<>();
            List<EstateRoom> roomList = estateRoomService.getRoomListByUserId(user_id,"");
            if(CollUtil.isNotEmpty(roomList)){
                for (EstateRoom estateRoom : roomList){
                    if(!estateIds.contains(estateRoom.getEstateId())){
                        estateIds.add(estateRoom.getEstateId());
                    }
                }
            }


            QueryWrapper<Survey> qw = new QueryWrapper<>();
            qw.eq("survey_type",survey_type);
            qw.eq("property_id",user.getPropertyId());
            if(is_my > 0){
                qw.eq("from_wx_user_id",user_id);
            }else{
                qw.eq("state",1);
                qw.eq("check_state",2);
            }
            qw.in("estate_id", estateIds);
            List<Survey> surveys = surveyService.list(qw);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",surveys.size(),surveys),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/list/new")
    public JSONObject listNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/list/new 接收的参数： "+requestParam);
            System.out.println("survey/list/new 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_type = jsonRequest.containsKey("survey_type") ? jsonRequest.getInt("survey_type") : 0;
            int is_my = jsonRequest.containsKey("is_my") ? jsonRequest.getInt("is_my") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            List<Integer> estateIds = new ArrayList<>();
            List<Integer> propertyIds = new ArrayList<>();
            List<EstateRoom> roomList = estateRoomService.getRoomListByUserId(user_id,"");
            if(CollUtil.isNotEmpty(roomList)){
                for (EstateRoom estateRoom : roomList){
                    if(!estateIds.contains(estateRoom.getEstateId())){
                        estateIds.add(estateRoom.getEstateId());
                    }

                    if(!propertyIds.contains(estateRoom.getPropertyId())){
                        propertyIds.add(estateRoom.getPropertyId());
                    }
                }
            }

            map.put("roomCount", roomList.size());
            List<Survey> surveys = new ArrayList<>();
            if(estateIds.size() > 0){
                QueryWrapper<Survey> qw = new QueryWrapper<>();
                qw.eq("survey_type",survey_type);
//            qw.eq("property_id",user.getPropertyId());
//            if(is_my > 0){
//                qw.eq("from_wx_user_id",user_id);
//            }else{
////                qw.eq("check_state",2);
//            }
//                qw.in("property_id", propertyIds);

                qw.eq("survey_type",survey_type);
                qw.eq("state",1);
                qw.in("estate_id", estateIds);
                qw.orderByDesc("id");
                surveys = surveyService.list(qw);
                map.put("surveys",surveys);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",surveys.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/question/list")
    public JSONObject questionList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/question/list 接收的参数： "+requestParam);
            System.out.println("survey/question/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            List<SurveyQuestion> questions = new ArrayList<>();
            if(survey.getState() == 1){
                QueryWrapper<SurveyQuestion> qw = new QueryWrapper<>();
                qw.eq("survey_id",survey_id);
                qw.eq("state",0);
                qw.orderByAsc("sort");
                questions = questionService.list(qw);
                if(CollUtil.isNotEmpty(questions)){
                    for (SurveyQuestion question : questions){
                        if(StrUtil.isNotEmpty(question.getAnswerSection())){
                            JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                            question.setSections(jsonArray);
                        }else{
                            question.setSections(new JSONArray());
                        }
                        if(question.getQuestionType() == 2){//图片类型
                            question.setFilePath(new String[0]);
                        }
                    }
                }
                map.put("questions",questions);
            }


            QueryWrapper<SysNotice> qwNotice = new QueryWrapper<>();
            qwNotice.eq("property_id", survey.getPropertyId());
            qwNotice.eq("estate_id", survey.getEstateId());
            qwNotice.eq("notice_type", 4);//公告类型（1通知 2公告 3 公共收益, 4 隐私协议 5 服务协议）
            qwNotice.eq("status", 0);
            qwNotice.last("limit 1");
            SysNotice notice = sysNoticeService.getOne(qwNotice);
            if(notice != null){
                map.put("statement", notice);
            }

            map.put("survey",survey);
            //调查问卷模板
            if(survey.getSurveyType() == 0){
                if(survey.getEstateId()!= null){
                    int surveyEstateId = survey.getEstateId();
                    long roomCount = estateRoomService.myRoomCountByEstateId(user_id, surveyEstateId);
                    map.put("roomCount",roomCount);
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", questions.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表(统一码模式)
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/question/list/new")
    public JSONObject questionListNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/question/list/new 接收的参数： "+requestParam);
            System.out.println("survey/question/list/new 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            int point_qr_id = jsonRequest.containsKey("point_qr_id") ? jsonRequest.getInt("point_qr_id") : 0;
            int point_qr_info_id = jsonRequest.containsKey("point_qr_info_id") ? jsonRequest.getInt("point_qr_info_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            EventPointQr pointQr = eventPointQrService.findById(point_qr_id);
            if(pointQr == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该点位不存在"),true,true);
            }


            EventPointQrInfo pointInfoQr = eventPointQrInfoService.findById(point_qr_info_id);
            if(pointInfoQr == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该点位事件类型未配置"),true,true);
            }


            Survey survey = surveyService.findById(pointInfoQr.getCheckTemplateId());
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷不存在"),true,true);
            }

            QueryWrapper<SurveyQuestion> qw = new QueryWrapper<>();
            qw.eq("survey_id",pointInfoQr.getCheckTemplateId());
            qw.eq("state",0);
            qw.orderByAsc("sort");
            List<SurveyQuestion> questions = questionService.list(qw);
            if(CollUtil.isNotEmpty(questions)){
                for (SurveyQuestion question : questions){
                    if(StrUtil.isNotEmpty(question.getAnswerSection())){
                        JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                        question.setSections(jsonArray);
                    }else{
                        question.setSections(new JSONArray());
                    }
                    if(question.getQuestionType() == 2){//图片类型
                        question.setFilePath(new String[0]);
                    }
                }
            }
            Map<String,Object> map = new HashMap<>();


            QueryWrapper<SysNotice> qwNotice = new QueryWrapper<>();
            qwNotice.eq("property_id", survey.getPropertyId());
            qwNotice.eq("estate_id", survey.getEstateId());
            qwNotice.eq("notice_type", 4);
            qwNotice.eq("status", 0);
            qwNotice.last("limit 1");
            SysNotice notice = sysNoticeService.getOne(qwNotice);
            if(notice != null){
                map.put("statement", notice);
            }

            map.put("questions",questions);
            map.put("survey",survey);
            //调查问卷模板
            if(survey.getSurveyType() == 0){
                int surveyEstateId = survey.getEstateId();
                long roomCount = estateRoomService.myRoomCountByEstateId(user_id, surveyEstateId);
                map.put("roomCount",roomCount);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",questions.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/question/detail")
    public JSONObject questionDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int question_id = jsonRequest.containsKey("question_id") ? jsonRequest.getInt("question_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            if(question_id > 0){
                SurveyQuestion question = questionService.findById(question_id);
                if(question == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
                }
                map.put("question",question);
            }
            map.put("survey",survey);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int question_id = jsonRequest.containsKey("question_id") ? jsonRequest.getInt("question_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
            }

//            SurveyQuestion question = questionService.findById(question_id);
//            if(question == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
//            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",survey),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/record/detailById")
    public JSONObject userRecordDetailById(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
//            }

            SurveyUserRecord userRecord = surveyUserRecordService.getById(record_id);
            if(userRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该记录不存在"),true,true);
            }

            Survey survey = surveyService.findById(userRecord.getSurveyId());
            map.put("survey", survey);



            QueryWrapper<SurveyQuestion> qwQuestion = new QueryWrapper<>();
            qwQuestion.eq("survey_id", userRecord.getSurveyId());
            List<SurveyQuestion> questions = questionService.list(qwQuestion);
            if(CollUtil.isNotEmpty(questions)){
                for (SurveyQuestion question : questions){

                    List<String> imgList = new ArrayList<>();
                    QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
                    qwInfo.eq("record_id", userRecord.getId());
                    qwInfo.eq("question_id", question.getId());
                    qwInfo.orderByDesc("id");
                    List<SurveyUserRecordInfo> recordInfos = surveyUserRecordInfoService.list(qwInfo);
                    if(CollUtil.isNotEmpty(recordInfos)){
                        for (SurveyUserRecordInfo info : recordInfos){
                            info.setQuestionTitle(question.getQuestionTitle());
                            //问题的类型 0 - 选择项  1-  输入项  2 - 图片
                            if(question.getQuestionType() == 0){
                                String answerSection = question.getAnswerSection();
                                JSONArray jsonArray = JSONUtil.parseArray(answerSection);
                                List<SurveyQuestionSectionDto> sectionDtos = jsonArray.toList(SurveyQuestionSectionDto.class);
                                String section = sectionDtos.get(Integer.parseInt(info.getAnswer())).getValue();
                                info.setAnswerTxt(section);
                            }else if(question.getQuestionType() == 1){
                                info.setAnswerTxt(info.getAnswer());
                            }
                            if(info.getIsImg() == 1){
                                info.setImgUrl(imgPrefix + info.getAnswer());
                                imgList.add(imgPrefix + info.getAnswer());
                            }
                        }
                    }
                    question.setImgList(imgList);
                    question.setRecordInfos(recordInfos);
                }
            }
            map.put("questions", questions);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", questions.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/recordDetail")
    public JSONObject userRecordDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int task_info_id = jsonRequest.containsKey("task_info_id") ? jsonRequest.getInt("task_info_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
            qw.eq("event_task_info_id", task_info_id);
            qw.orderByDesc("id");
            qw.last("limit 1");
            SurveyUserRecord userRecord = surveyUserRecordService.getOne(qw);
            if(userRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该记录不存在"),true,true);
            }

            Survey survey = surveyService.findById(userRecord.getSurveyId());
            map.put("survey", survey);



            QueryWrapper<SurveyQuestion> qwQuestion = new QueryWrapper<>();
            qwQuestion.eq("survey_id", userRecord.getSurveyId());
            List<SurveyQuestion> questions = questionService.list(qwQuestion);
            if(CollUtil.isNotEmpty(questions)){
                for (SurveyQuestion question : questions){

                    List<String> imgList = new ArrayList<>();
                    QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
                    qwInfo.eq("record_id", userRecord.getId());
                    qwInfo.eq("question_id", question.getId());
                    qwInfo.orderByDesc("id");
                    List<SurveyUserRecordInfo> recordInfos = surveyUserRecordInfoService.list(qwInfo);
                    if(CollUtil.isNotEmpty(recordInfos)){
                        for (SurveyUserRecordInfo info : recordInfos){
                            info.setQuestionTitle(question.getQuestionTitle());
                            //问题的类型 0 - 选择项  1-  输入项  2 - 图片
                            if(question.getQuestionType() == 0){
                                String answerSection = question.getAnswerSection();
                                JSONArray jsonArray = JSONUtil.parseArray(answerSection);
                                List<SurveyQuestionSectionDto> sectionDtos = jsonArray.toList(SurveyQuestionSectionDto.class);
                                String section = sectionDtos.get(Integer.parseInt(info.getAnswer())).getValue();
                                info.setAnswerTxt(section);
                            }else if(question.getQuestionType() == 1){
                                info.setAnswerTxt(info.getAnswer());
                            }
                            if(info.getIsImg() == 1){
                                info.setImgUrl(imgPrefix + info.getAnswer());
                                imgList.add(imgPrefix + info.getAnswer());
                            }
                        }
                    }
                    question.setImgList(imgList);
                    question.setRecordInfos(recordInfos);
                }
            }
            map.put("questions", questions);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", questions.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addRecord")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int task_id = jsonRequest.containsKey("task_id") ? jsonRequest.getInt("task_id") : 0;
            int task_info_id = jsonRequest.containsKey("task_info_id") ? jsonRequest.getInt("task_info_id") : 0;
            int target_id = jsonRequest.containsKey("target_id") ? jsonRequest.getInt("target_id") : 0;
            int point_qr_id = jsonRequest.containsKey("point_qr_id") ? jsonRequest.getInt("point_qr_id") : 0;
            int point_qr_info_id = jsonRequest.containsKey("point_qr_info_id") ? jsonRequest.getInt("point_qr_info_id") : 0;

            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0d;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0d;

            String answer = jsonRequest.containsKey("answer") ? jsonRequest.getStr("answer") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷不存在"),true,true);
            }
            if(survey.getState() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷已停用"),true,true);
            }

            SysUser sysUser = null;
            if(survey.getSurveyType() == 1 || survey.getSurveyType() == 2){
                sysUser = sysUserService.findById(user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定工作人员账号"),true,true);
                }

                //判断当前操作任务是否是今天的
                EventPlanTask task = eventPlanTaskService.findById(task_id);
                if(task != null){
                    if(new Date().getTime() < task.getBeginTime().getTime() || task.getEndTime().getTime() < new Date().getTime()){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请在规定时间内进行打卡"),true,true);
                    }
                }

            }else if(survey.getSurveyType() == 0) {
                if(survey.getId() != 374){
                    QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
                    qw.select("id");
                    qw.eq("survey_id", survey_id);
                    qw.eq("user_id", user_id);
                    long recordCount = surveyUserRecordService.count(qw);
                    if (recordCount > 0) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "您已参与过该调查问卷"), true, true);
                    }
                }

                /**
                 * 是否是开放性的问卷 0 - 不是 1 - 是
                 */
                if(survey.getIsPublic() == 0){
                    if(user.getEstateId() == null || user.getEstateId() == 0){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定小区"),true,true);
                    }

                    long roomCount = estateRoomService.myRoomCountByEstateId(user_id,user.getEstateId());
                    if(roomCount == 0){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请绑定本小区房屋后提交"),true,true);
                    }
                }

            }
            if(StrUtil.isEmpty(answer)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请输入答案"),true,true);
            }


            int ret = surveyUserRecordService.addRecord(survey_id,task_id, task_info_id, target_id, point_qr_id, point_qr_info_id, user, sysUser, answer, lng, lat);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功",ret),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请求失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject add(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_type = jsonRequest.containsKey("survey_type") ? jsonRequest.getInt("survey_type") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            String title = jsonRequest.containsKey("title") ? jsonRequest.getStr("title") : null;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请您先绑定小区后再发布!"),true,true);
            }

            Survey survey = null;
            if(survey_id > 0){
                survey = surveyService.findById(survey_id);
            }else{
                survey = new Survey();
                survey.setState(0);
                survey.setCheckState(0);
                survey.setCheckSysUserId(0);
                survey.setCreateTime(new Date());
                survey.setFromType(1);
                survey.setFromWxUserId(user_id);
                survey.setPropertyId(user.getPropertyId());
                survey.setEstateId(user.getEstateId());
                survey.setSurveyType(survey_type);

                Estate estate = estateService.findById(user.getEstateId());
                if(estate!=null){
                    survey.setEstateName(estate.getEstateName());
                    Property property = propertyService.findById(estate.getPropertyId());
                    if(property!=null){
                        survey.setPropertyName(property.getPropertyName());
                    }
                }
            }

            survey.setQuestionTitle(title);
            survey.setQuestion(content);
            boolean ret = false;
            if(survey_id > 0){
                ret = surveyService.updateById(survey);
            }else{
                ret = surveyService.save(survey);
            }
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功，请设置公投选项！",survey),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请求失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  提交审核操作
     * @param
     * @throws Exception
     */
    @PostMapping(value="/regCheck")
    public JSONObject regCheck(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该公投信息不存在"),true,true);
            }

            QueryWrapper<SurveyQuestion> qw = new QueryWrapper<>();
            qw.select("id");
            qw.eq("survey_id",survey_id);
            long quesCount = questionService.count(qw);
            if(quesCount == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未设置公投问题选项，不能提交审核"),true,true);
            }

            if(survey.getCheckState() == 0 || survey.getCheckState() == 3){
                survey.setCheckState(1);
                boolean ret = surveyService.updateById(survey);
                if(ret){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"审核申请发送成功"),true,true);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"审核申请发送失败"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该状态下无需提交审核"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/delete")
    public JSONObject delete(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请您先绑定小区后再发布!"),true,true);
            }


            Survey survey = surveyService.findById(survey_id);
            if(survey != null){
                if(survey.getFromWxUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该项公投不属于你，不能删除!"),true,true);
                }
            }

            int ret = surveyService.addSurvey(user_id,survey);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/delete/question")
    public JSONObject deleteQuestion(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            System.out.println("survey/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int question_id = jsonRequest.containsKey("question_id") ? jsonRequest.getInt("question_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请您先绑定小区后再发布!"),true,true);
            }


            Survey survey = surveyService.findById(survey_id);
            if(survey != null){
                if(survey.getFromWxUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该项公投不属于你，不能删除!"),true,true);
                }
            }

            QueryWrapper<SurveyQuestion> qw= new QueryWrapper<>();
            qw.eq("survey_id",survey_id);
            qw.eq("id",question_id);
            SurveyQuestion question = questionService.getOne(qw);
            if(question == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问题项不存在"),true,true);
            }

            boolean ret = questionService.removeById(question_id);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加问卷问题项详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/question")
    public JSONObject addQuestion(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "survey/add/question 接收的参数： "+requestParam);
            System.out.println("survey/add/question 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            String question = jsonRequest.containsKey("question") ? jsonRequest.getStr("question") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请您先绑定小区后再发布!"),true,true);
            }

            boolean bl = false;
            SurveyQuestion surveyQuestion = JSONUtil.toBean(question,SurveyQuestion.class);
            if(surveyQuestion.getId()!=null && surveyQuestion.getId() > 0){
                bl = questionService.updateById(surveyQuestion);
            }else{
                surveyQuestion.setSurveyId(survey_id);
                surveyQuestion.setCreateTime(new Date());
                bl = questionService.save(surveyQuestion);
            }
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"保存失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 问题的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("record_id") int record_id,@RequestParam("user_id") int user_id,
                                @RequestParam("question_id") int question_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            SurveyUserRecord record = surveyUserRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_SURVEY_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date()) + "/" + fileName;

                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certurl.getInputStream(),fileName,upload_type);

                                        SurveyUserRecordInfo img = new SurveyUserRecordInfo();
                                        img.setAnswer(img_key);
                                        img.setUserId(user_id);
                                        img.setRecordId(record_id);
                                        img.setQuestionId(question_id);
                                        img.setCreateTime(new Date());
                                        img.setIsImg(1);
                                        surveyUserRecordInfoService.save(img);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
